import type { Direction, GameStatus, Point } from '../types'

export function useSnakeGame(boardSize: number) {
  // 初始化蛇的身体（三节，从左到右）
  const snake = ref<Point[]>([
    { x: 2, y: 0 },
    { x: 1, y: 0 },
    { x: 0, y: 0 },
  ])

  // 初始化食物位置
  const food = ref<Point>({ x: 5, y: 5 })

  // 当前移动方向
  const direction = ref<Direction>('right')

  // 用户下一次操作的方向（防止连续转两次导致撞到自己）
  const nextDirection = ref<Direction | null>(null)

  // 当前游戏状态（idle, running, paused, gameover）
  const status = ref<GameStatus>('idle')

  // 当前分数
  const score = ref<number>(0)

  // 定时器 ID
  const timer = ref(null)

  // 根据方向返回移动的增量
  function getDelta(dir: Direction) {
    switch (dir) {
      case 'up': return { dx: 0, dy: -1 }
      case 'down': return { dx: 0, dy: 1 }
      case 'left': return { dx: -1, dy: 0 }
      case 'right': return { dx: 1, dy: 0 }
    }
  }

  // 生成新的食物位置（不能出现在蛇身上）
  function randomFoodPosition(): Point {
    while (true) {
      const pos = {
        x: Math.floor(Math.random() * boardSize),
        y: Math.floor(Math.random() * boardSize),
      }
      if (!snake.value.some(s => s.x === pos.x && s.y === pos.y)) {
        return pos
      }
    }
  }

  // 设置方向，防止反向操作
  function setDirection(dir: Direction) {
    if (
      (direction.value === 'up' && dir === 'down')
      || (direction.value === 'down' && dir === 'up')
      || (direction.value === 'left' && dir === 'right')
      || (direction.value === 'right' && dir === 'left')
    ) {
      return
    }
    nextDirection.value = dir
  }

  // 游戏结束逻辑
  function gameOver(onGameOver?: () => void) {
    status.value = 'gameover'
    if (timer.value !== null) {
      clearInterval(timer.value)
      timer.value = null
    }
    onGameOver?.()
  }

  // 移动蛇（检查碰撞、吃食物、加分、更新位置）
  function moveSnake(onGameOver?: () => void) {
    if (nextDirection.value) {
      direction.value = nextDirection.value
      nextDirection.value = null
    }

    const { dx, dy } = getDelta(direction.value)
    const head = snake.value[0]
    const newHead = { x: head.x + dx, y: head.y + dy }

    // 撞墙
    if (
      newHead.x < 0
      || newHead.x >= boardSize
      || newHead.y < 0
      || newHead.y >= boardSize
    ) {
      gameOver(onGameOver)
      return
    }

    // 撞自己
    if (snake.value.some(seg => seg.x === newHead.x && seg.y === newHead.y)) {
      gameOver(onGameOver)
      return
    }

    // 移动：头部前进
    snake.value.unshift(newHead)

    // 吃到食物
    if (newHead.x === food.value.x && newHead.y === food.value.y) {
      score.value += 10
      food.value = randomFoodPosition()
    }
    else {
      // 没吃到食物则尾部减一
      snake.value.pop()
    }
  }

  // 开始游戏
  function startGame(onGameOver?: () => void, speed = 150) {
    if (status.value === 'running')
      return
    status.value = 'running'

    if (timer.value !== null) {
      clearInterval(timer.value)
      timer.value = null
    }

    timer.value = setInterval(() => {
      moveSnake(onGameOver)
    }, speed) as any
  }

  // 暂停游戏
  function pauseGame() {
    if (status.value !== 'running')
      return
    status.value = 'paused'
    if (timer.value !== null) {
      clearInterval(timer.value)
      timer.value = null
    }
  }

  // 恢复游戏
  function resumeGame(speed = 150) {
    if (status.value !== 'paused')
      return
    status.value = 'running'
    timer.value = setInterval(() => {
      moveSnake() // ⚠️ 这里没传 onGameOver
    }, speed) as any
  }

  // 重置游戏
  function resetGame() {
    if (timer.value !== null) {
      clearInterval(timer.value)
      timer.value = null
    }

    snake.value = [
      { x: 2, y: 0 },
      { x: 1, y: 0 },
      { x: 0, y: 0 },
    ]

    food.value = randomFoodPosition()
    direction.value = 'right'
    nextDirection.value = null
    status.value = 'idle'
    score.value = 0
  }

  return {
    snake,
    food,
    direction,
    score,
    status,
    setDirection,
    startGame,
    pauseGame,
    resumeGame,
    resetGame,
  }
}
